// @ts-nocheck

const {convertDates}=require('./public/plugin.js')
const {globalLogger}=require('./winstonLogger.js')
const express = require('express');
const expressWinston = require('express-winston');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const jwt = require('jsonwebtoken')
// 跨域
const cors = require('cors')
const {successMsg,errorMsg,security_key}=require('./public/constant.js')
const app = express();
app.use(cors())
// 解析 POST 请求主体
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({
  secret: 'my secret',
  resave: false,  // 重新保存
  saveUninitialized: true  // 自动保存
}));
app.use(expressWinston.logger({
  winstonInstance: globalLogger,
  meta: true, // 如果设置为 true，则会在日志中添加一些元数据，例如请求的 URL、方法、HTTP 版本等
  msg: "HTTP {{req.method}} {{req.url}}", // 日志消息的格式。你可以使用双大括号 {{}} 来引用请求或响应的属性。
  expressFormat: true, // 如果设置为 true，则日志消息的格式会类似于 Express 的默认日志格式 :method :url :status :response-time ms - :res[content-length]。
  colorize: true, // 如果设置为 true，则日志消息会被着色
  requestWhitelist: ['url', 'headers', 'method', 'httpVersion', 'originalUrl', 'query','body','ip'],// 一个数组，用于指定哪些请求属性应该被记录
  ignoreRoute: function (req, res) { return false; } // 
}));
app.use(express.static('assets'));

const noNeedToken=['/Admin/Login','/Admin/Add']
app.use((req, res, next) => {
  if(noNeedToken.includes(req.originalUrl)){
    next()
  }else{
    const token = req.headers['authorization']||req.headers['token'];
    if (!token) {
      return res.status(401).send(errorMsg('无法获取token'));
    }
    try {
      const decoded = jwt.verify(token, security_key);
      console.log(decoded)
      next(); // 继续执行后续中间件或路由处理器
    } catch(err) {
      if(err.name === 'TokenExpiredError') {
        return res.status(401).send(errorMsg('token已过期'));
      } else {
        return res.status(401).send(errorMsg('不合法的token'));
      }
    }
  }
});
app.use(convertDates)

const uploadRouter = require('./api/upload.js')
app.use('/Upload',uploadRouter)
const adminRouter = require('./api/admin.js');
app.use('/Admin', adminRouter);
const roleRouter = require('./api/role.js');
app.use('/Role', roleRouter);
const roomTypeRouter = require('./api/roomType.js');
app.use('/RoomType', roomTypeRouter);
const roomStateRouter = require('./api/roomState.js');
app.use('/RoomState', roomStateRouter);
const roomRouter = require('./api/room.js');
app.use('/Room', roomRouter);
const guestRouter = require('./api/guest.js');
app.use('/Guest', guestRouter);
const orderRouter = require('./api/order.js');
app.use('/Order', orderRouter);

app.listen(3000, () => {
  console.log('Server started on port 3000');
});